#include "protocol.h"

void initialize_header (Header* hdr, unsigned short int message_id, char ack_mode, char type, char* orig_id, char* dest_id){
	hdr->id = message_id;
    hdr->type = type;
    strcpy(hdr->orig_id, orig_id);
    strcpy(hdr->dest_id, dest_id);
}

int encapsula(char** block, char* msg, Header* hdr){

	int i = 0;	

	int msg_len = strlen(msg) * sizeof(char);
	int length_block = sizeof(Header) + msg_len;

	*(block) = (char*) malloc(length_block);

	//converting shor int types in header from host type order to network type order
	hdr->id = htons(hdr->id);
	//hdr->type = htons(hdr->type);
	hdr->tam_msg = htons(strlen(msg));

	//mounting full block
	*((Header*) &((*block)[i])) = *hdr;
	i += sizeof(Header);
	
	int k;
	for (k = 0; k < strlen(msg); k++)
		(*block)[i++] = msg[k];

    return length_block;
}

void desencapsula(char* block, char** msg, Header* hdr){

	int i = 0;    

	/* Desmonta bloco */
    // Cabecalho
    *hdr = *((Header*) &(block[i]));
    i += sizeof(Header);

	hdr->id = ntohs(hdr->id);
	//hdr->type = ntohs(hdr->type);
	hdr->tam_msg = ntohs(hdr->tam_msg);
    /*
	printf("id:      %d\n", hdr->id);
	printf("type:    %d\n", hdr->type);
	printf("origem:  %s\n", hdr->orig_id);
	printf("destino: %s\n", hdr->dest_id);
	*/

	*msg = (char*) malloc((hdr->tam_msg + 1) * sizeof(char));

	int k;
	for(k = 0; k < hdr->tam_msg; k++)
		(*msg)[k] = block[i++];
	(*msg)[k] = '\0';

	//printf("message: %s\n", *msg);
}


